import { message } from 'ant-design-vue'
import { ExtractPropTypes, onMounted, PropType, ref } from 'vue'
import { OptionItem } from '../types'

export const remoteWidgetPropDefine = {
  remoteLoad: {
    type: Function
  },
  options: {
    type: Array as PropType<OptionItem[]>,
    default: () => []
  }
} as const

export type RemoteWidgetProp = ExtractPropTypes<typeof remoteWidgetPropDefine>

export default function useRemoteData(prop: RemoteWidgetProp) {
  const { options, remoteLoad } = prop
  const resultOptions = ref(options)
  const optionsLoading = ref(false)
  onMounted(async () => {
    if (!remoteLoad) return
    try {
      optionsLoading.value = true
      const result = await remoteLoad()
      resultOptions.value = result
    } catch {
      message.error('选项加载失败')
    } finally {
      optionsLoading.value = false
    }
  })
  return {
    options: resultOptions,
    optionsLoading
  }
}
